<template>
  <div>
    <el-table :data="permissonList" border stripe row-key="id" :expand-row-keys="expandKeys">
      <el-table-column label="名称" prop="name" width="300" />
      <el-table-column label="权限值" prop="code" width="300" />
      <el-table-column label="跳转权限值" prop="toCode" width="300" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            @click="showDialog(row)"
            size="small"
            type="primary"
            :icon="Plus"
            :disabled="row.type === 2"
          />
          <el-button
            @click="editDialog(row)"
            size="small"
            type="warning"
            :icon="Edit"
            :disabled="row.pid === '0'"
          />
          <el-button @click="removeMenuBtn(row)" size="small" type="danger" :icon="Delete" />
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
      align-center
      :before-close="handleClose"
    >
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="permissionRules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="dialogForm.name" />
        </el-form-item>
        <el-form-item label="权限功能值" prop="code">
          <el-input v-model="dialogForm.code" />
        </el-form-item>
        <el-form-item label="跳转路由权限制" v-if="titleStatus !== 1 && titleStatus !== 2">
          <el-input v-model="dialogForm.toCode" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="dialogConfirm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, ref } from 'vue'
import { reqAddMenu, reqDelMenu, reqPermissionList, reqUpdateMenu } from '@/api/permissionList'
import type { IPermissonChild, IReqAddMenu } from '@/types/permissionList'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'

// 是否展示弹框
const dialogVisible = ref(false)
const dialogFormRef = ref<FormInstance>()
// 新增菜单、功能弹窗
const dialogForm = ref<IReqAddMenu>({
  code: '',
  level: '',
  name: '',
  pid: '',
  toCode: '',
  type: ''
})
// 控制弹框的状标题
const titleStatus = ref()

// 菜单管理列表数据
const permissonList = ref<IPermissonChild[]>()
// 设置目前的展开行
const expandKeys = ref<string[]>(['1'])
// 是否是编辑
const isEdit = ref()

// 编辑的弹框
const editDialog = (row: IPermissonChild) => {
  isEdit.value = true
  dialogVisible.value = true

  nextTick(() => {
    dialogForm.value = JSON.parse(JSON.stringify(row))
    // 控制弹框的标题
    titleStatus.value = row.level
  })
}

// 点击展示弹框
const showDialog = (row: IPermissonChild) => {
  dialogFormRef.value?.resetFields()

  // 是否是编辑
  isEdit.value = false
  // 控制弹框的标题
  titleStatus.value = row.level
  // 展示弹框
  dialogVisible.value = true

  // 获取父级的 Id
  dialogForm.value.pid = row.id as string

  switch (row.level) {
    case 1:
      dialogForm.value.level = 2
      dialogForm.value.type = 1
      break

    case 2:
      dialogForm.value.level = 3
      dialogForm.value.type = 1
      break

    case 3:
      dialogForm.value.level = 4
      dialogForm.value.type = 2
      break
  }
}

// 关闭弹框
const handleClose = () => {
  dialogForm.value = {} as IReqAddMenu

  dialogFormRef.value?.resetFields()
  dialogVisible.value = false
}

// 弹框确认按钮
const dialogConfirm = () => {
  // 兜底验证
  dialogFormRef.value?.validate(async (valid) => {
    if (!valid) return

    // 调用 API，实现新增功能
    const res = isEdit.value
      ? await reqUpdateMenu(dialogForm.value)
      : await reqAddMenu(dialogForm.value)

    if (res.code === 20000) {
      // 获取权限列表
      getPermissonList()
      // 关闭弹框，清空内容
      handleClose()
      // 给用户提示
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    }
  })
}

// 获取菜单列表
const getPermissonList = async () => {
  const res = await reqPermissionList()

  if (res.code === 20000) {
    permissonList.value = res.data.children
  }
}

// 新增弹框的标题
const dialogTitle = computed(() => {
  if (titleStatus.value === 1 || titleStatus.value === 2) {
    return isEdit.value ? '编辑菜单' : '新增菜单'
  } else if (titleStatus.value === 3) {
    return isEdit.value ? '编辑菜单' : '新增菜单'
  }

  return isEdit.value ? '编辑菜单' : '新增菜单'
})

// 表单验证规则
const permissionRules = computed(() => {
  // 菜单权限校验的规则
  const menuRules = {
    name: [{ required: true, message: '名称必须输入', trigger: 'blur' }],
    code: [{ required: true, message: '权限值必须输入', trigger: 'blur' }]
  }
  // 按钮功能权限校验的规则
  const btnRules = {
    name: [{ required: true, message: '名称必须输入', trigger: 'blur' }],
    code: [{ required: true, trigger: 'blur', message: '功能权限值必须输入' }]
  }

  return dialogForm.value.level === 4 ? btnRules : menuRules
})

// 删除菜单和按钮
const removeMenuBtn = (row: IPermissonChild) => {
  ElMessageBox.confirm('确认删除该用户?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await reqDelMenu(row.id as string)
      ElMessage({
        type: 'success',
        message: '商品删除成功'
      })
      getPermissonList()
    })
    .catch(() => {
      ElMessage.info('商品删除失败')
    })
}

onMounted(() => {
  getPermissonList()
})
</script>

<script lang="ts">
export default {
  name: 'PermissionList'
}
</script>

<style lang="scss" scoped></style>
